﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Configuration;
using System.IO;
using MainConsoleService.Common;

namespace DownOrderApplication
{
    public partial class FrmDoOrder : Form
    {
        private static TaskClass objTask = new TaskClass();
        //订单下载线程
        private Thread MainThread;
        //订单发货线程
        private Thread SendGoodsThread;
        //订单出库线程
        private Thread OutStockThread;
        //订单退款线程
        private Thread RefundThread;
        //订单迁移线程
        private Thread MoveThread;
        //会员迁移线程
        private Thread MemberThread;
        //库存更新线程
        private Thread StockNumThread;


        private string isAuto = "";
        private static bool bSetStop;
        private static bool bStarted;
        private static readonly string logPath = AppDomain.CurrentDomain.BaseDirectory;

        public FrmDoOrder()
        {
            InitializeComponent();
            MainThread = new Thread(new ThreadStart(delegate() { ThreadFunc("Main"); }));
            MainThread.Priority = ThreadPriority.Highest;

            SendGoodsThread = new Thread(new ThreadStart(delegate() { ThreadFunc("SendGoods"); }));
            SendGoodsThread.Priority = ThreadPriority.Normal;

            RefundThread = new Thread(new ThreadStart(delegate() { ThreadFunc("Refund"); }));
            RefundThread.Priority = ThreadPriority.Normal;

            OutStockThread = new Thread(new ThreadStart(delegate() { ThreadFunc("OutStock"); }));
            OutStockThread.Priority = ThreadPriority.Normal;

            MoveThread = new Thread(new ThreadStart(delegate() { ThreadFunc("Move"); }));
            MoveThread.Priority = ThreadPriority.BelowNormal;

            MemberThread = new Thread(new ThreadStart(delegate() { ThreadFunc("Member"); }));
            MemberThread.Priority = ThreadPriority.BelowNormal;

            StockNumThread = new Thread(new ThreadStart(delegate() { ThreadFunc("StockNum"); }));
            StockNumThread.Priority = ThreadPriority.BelowNormal;

        }

        private void ThreadDoOrder_Load(object sender, EventArgs e)
        {
            if (!Directory.Exists(logPath + "log"))
            {
                Directory.CreateDirectory(logPath + "\\log");
            }
            isAuto = ConfigurationManager.AppSettings["isAuto"].Trim();
            notifyIcon1.BalloonTipText = "系统服务已经开启，系统服务开始运行!";
            notifyIcon1.BalloonTipTitle = "OrderDownTool Service";
            notifyIcon1.ShowBalloonTip(2);
            this.Visible = false;
            if (isAuto == "1")
            {
                txtStartService_Click(sender, e);
            }            
        }



        public static void SetStop()
        {
            bSetStop = true;
            System.DateTime TimeMarkStart = System.DateTime.Now;
            DateTime TimeMark = TimeMarkStart.AddSeconds(5);
            while (true)
            {
                System.Threading.Thread.Sleep(2000);
                if (!bStarted)
                {
                    break;
                }
                System.DateTime CurrentTime = System.DateTime.Now;
                if (CurrentTime > TimeMark)
                {
                    break;
                }
            }
        }

        public static void ThreadFunc(string threadType)
        {           
            bStarted = true;
            /*	系统服务心跳，单位：秒	*/
            double setHeart = 1;
            /*	任务调用默认间隔，单位：分钟	*/
            int setTaskTimeDefault = 30;
            int setTaskTime;           
            string TaskRunTime = "";
            switch (threadType)
            {
                case "Main":
                    TaskRunTime = ConfigurationManager.AppSettings["DownOrderTime"].Trim();
                    break;
                case "Refund":
                    TaskRunTime = ConfigurationManager.AppSettings["RefundTime"].Trim();
                    break;
                case "SendGoods":
                    TaskRunTime = ConfigurationManager.AppSettings["SendGoodsTime"].Trim();
                    break;
                case "OutStock":
                    TaskRunTime = ConfigurationManager.AppSettings["OutStockTime"].Trim();
                    break;
                case "Member":
                    TaskRunTime = ConfigurationManager.AppSettings["MemberTime"].Trim();
                    break;
                case "Move":
                    TaskRunTime = ConfigurationManager.AppSettings["MoveTime"].Trim();
                    break;
                case "StockNum":
                    TaskRunTime = ConfigurationManager.AppSettings["StockNumTime"].Trim();
                    break;
            }
            try
            {
                int nTaskRunTime = int.Parse(TaskRunTime);
                // 判断读取的任务运行间隔时间是否大于一天或者小于1
                if (nTaskRunTime < 1 || nTaskRunTime > 1440)
                    setTaskTime = setTaskTimeDefault;
                else
                    setTaskTime = nTaskRunTime;
            }
            catch
            {
                // 异常情况使用默认值
                setTaskTime = setTaskTimeDefault;
            }

            DateTime dtLast = System.DateTime.Now;
            DateTime dtNow = System.DateTime.Now;
            TimeSpan ts;

            bool bFistRun = true;
            bool bTaskTime = false;
            /// <summary>
            /// 主循环
            /// </summary>
            while (true)
            {
                if (bSetStop)
                    break;
                System.Threading.Thread.Sleep((int)(setHeart * 1000));

                dtNow = System.DateTime.Now;
                ts = dtNow - dtLast;
                bTaskTime = (ts.Minutes >= setTaskTime) ? true : false;

                if (bFistRun || bTaskTime)
                {
                    dtLast = dtNow;
                    bFistRun = false;
                    objTask.Run(threadType);                    
                }
            }
            // 结束服务
            bStarted = false;
        }


        private void txtStartService_Click(object sender, EventArgs e)
        {
            bSetStop = false;
            if (MainThread.ThreadState == ThreadState.Unstarted)
            {
                MainThread.Start();
                WriteSysLog.Log("ServerLog_Main", string.Format("订单下载服务启动成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            if (RefundThread.ThreadState == ThreadState.Unstarted)
            {
                RefundThread.Start();
                WriteSysLog.Log("ServerLog_Refund", string.Format("订单退款服务启动成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            if (SendGoodsThread.ThreadState == ThreadState.Unstarted)
            {
                SendGoodsThread.Start();
                WriteSysLog.Log("ServerLog_SendGoods", string.Format("订单发货服务启动成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            if (OutStockThread.ThreadState == ThreadState.Unstarted)
            {
                OutStockThread.Start();
                WriteSysLog.Log("ServerLog_OutStock", string.Format("订单出库服务启动成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }

            if (MoveThread.ThreadState == ThreadState.Unstarted)
            {
                MoveThread.Start();
                WriteSysLog.Log("ServerLog_Move", string.Format("订单迁移服务启动成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }

            if (MemberThread.ThreadState == ThreadState.Unstarted)
            {
                MemberThread.Start();
                WriteSysLog.Log("ServerLog_Member", string.Format("会员迁移服务启动成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }

            if (StockNumThread.ThreadState == ThreadState.Unstarted)
            {
                StockNumThread.Start();
                WriteSysLog.Log("ServerLog_StockNum", string.Format("库存更新服务启动成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }



        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            txtEndService_Click(sender, e);
            Application.Exit();
        }

        private void txtEndService_Click(object sender, EventArgs e)
        {
            SetStop();
            MainThread.Abort();
            WriteSysLog.Log("ServerLog_Main", string.Format("订单下载服务终止成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            RefundThread.Abort();
            WriteSysLog.Log("ServerLog_Refund", string.Format("订单退款服务终止成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            SendGoodsThread.Abort();
            WriteSysLog.Log("ServerLog_SendGoods", string.Format("订单发货服务终止成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            OutStockThread.Abort();
            WriteSysLog.Log("ServerLog_OutStock", string.Format("订单出库服务终止成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            MoveThread.Abort();
            WriteSysLog.Log("ServerLog_Move", string.Format("订单迁移服务终止成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            MemberThread.Abort();
            WriteSysLog.Log("ServerLog_Member", string.Format("会员迁移服务终止成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));

            StockNumThread.Abort();
            WriteSysLog.Log("ServerLog_StockNum", string.Format("库存更新服务终止成功！{0}\r\n", System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));


        }

        private void btnServerToolKit_Click(object sender, EventArgs e)
        {
           
        }
    }
}
